#include<iostream>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;
void Writer(int wfd)//向管道内写入的函数
{
    char buffer[128]="我已向管道写入，请接收！";
    int cnt=0;
    while(1)
    {
        snprintf(buffer,sizeof(buffer),"我是子进程,我的pid是: %d ,cnt: %d\n",getpid(),cnt);//将格式化字符串拼接到buffer
        write(wfd,buffer,sizeof(buffer));//写入
        cnt++;
        sleep(1);//睡眠一秒
    }
}

void Reader(int rfd)//读取管道内容的函数
{
    char buffer[1024];
    int cnt=5;
    while(cnt--)
    {
        read(rfd,buffer,sizeof(buffer));//子进程将读取到的数据存放入buffer
        printf("father get message: %s",buffer);
    }

}
int main()
{
    int pipefd[2]{0};//接收文件描述符的输出型参数
    int n=pipe(pipefd);
    if(n<0)
    return -1;
    pid_t pid=fork();
    if(pid==0)//子进程保留写，并对管道进行写入
    {
        close(pipefd[0]);//关闭读
        Writer(pipefd[1]);
        exit(0);
    }
    //父进程对管道进行读取，关闭写
    close(pipefd[1]);
    Reader(pipefd[0]);
    close(pipefd[0]);//关闭读端
    int status=0;
    wait(&status);
    int ret=status&0x7F;
    if(ret!=0)//当读端关闭，写进程会被OS强制终结
    cout<<"子进程已被杀死，杀手信号为："<<ret<<endl;
    return 0;
}